<template>
  <form-wrap :rules="rules" :schema="formSchema" @register="formRegister" />
</template>
<script setup lang="ts">
  import { getApi } from '@/api/system/role';
  import { useForm } from '@/hooks/form';
  import { useValidator } from '@/hooks/validator';
  import { useDictStore } from '@/store';

  const dictStore = useDictStore();
  const { required, limitLetterDigit } = useValidator();
  const currentCode = ref();

  const props = defineProps({
    currentId: {
      type: String,
      default: () => null,
    },
  });
  const disabledCode = computed(() => {
    return dictStore.getItems('DefaultRole')?.some((item) => {
      return item.extend.code === currentCode.value;
    });
  });
  const formSchema = reactive<FormSchema[]>([
    { field: 'id', hidden: true },
    {
      field: 'code',
      label: '编码',
      type: 'Input',
      props: {
        maxlength: 30,
        disabled: disabledCode,
      },
    },
    {
      field: 'name',
      label: '名称',
      type: 'Input',
      componentProps: { maxlength: 50 },
    },
    {
      field: 'remark',
      label: '备注',
      type: 'Input',
      componentProps: {
        type: 'textarea',
        rows: 3,
        maxlength: 200,
      },
    },
  ]);

  const rules = reactive({
    code: [required(), limitLetterDigit()],
    name: [required()],
  });

  const { formRegister, formMethods } = useForm();
  const { setValues, submitForm } = formMethods;

  const submit = async () => {
    return await submitForm();
  };

  watch(
    () => props.currentId,
    async (currentId) => {
      const res = await getApi(currentId);
      currentCode.value = res.code;
      setValues(res);
    },
    {
      deep: true,
      immediate: true,
    }
  );

  defineExpose({
    submit,
  });
</script>
